package Plagger::Plugin::Filter::YomiHiraGana;

use strict;
use base qw( Plagger::Plugin );
use Text::MeCab;
use Unicode::Japanese;

sub register {
    my ( $self, $context ) = @_;
    $context->register_hook( 
        $self, 
        'update.entry.fixup' => \&update,
    );
}

sub update {
    my ( $self, $context, $args ) = @_;
    my $title = $args->{entry}->title;
    my $body  = $args->{entry}->body;
    $title = $self->add_hiragana($title);
    $body  = $self->add_hiragana($body);
    $args->{entry}->title($title);
    $args->{entry}->body($body);
}

sub add_hiragana {
    my ( $self, $string ) = @_;
    my $mecab  = Text::MeCab->new();
    my $markup = $self->conf->{markup};
    my $hiragana_string;
    for ( my $node = $mecab->parse($string) ; $node ; $node = $node->next ) {
        my $kana     = ( split( ',', $node->feature ) )[7];
        my $s        = Unicode::Japanese->new();
        my $code     = $s->getcode( $node->surface );
        my $hiragana = $s->set($kana)->kata2hira->get;
        if (   $hiragana
            && $hiragana ne "*"
            && $hiragana ne $node->surface
            && $kana     ne $node->surface
            && $code     ne "ascii" ) {
            if ($markup) {
                $hiragana_string .= "<ruby>" . $node->surface . "<rp>(</rp><rt>$hiragana</rt><rp>)</rp></ruby>";
            } else {
                $hiragana_string .= $node->surface . "($hiragana)";
            }
        } elsif ( $code ne "unknown" ) {
            $hiragana_string .= $node->surface;
        }
    }
    Encode::decode_utf8($hiragana_string);
}

1;

__END__

=head1 NAME

Plagger::Plugin::Filter::YomiHiraGana - add YomiHiraGana

=head1 SYNOPSIS

  - module: Filter::YomiHiraGana

=head1 DESCRIPTION


=head1 EXAMPLE


=head1 AUTHOR

Akihito Takeda

=head1 SEE ALSO

L<Plagger>, L<Text::MeCab>

=cut
